package com.li.network.socket.UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author li
 * @date 2023/6/14 14:20
 */
public class UDPServer {
    public static void main(String[] args) throws IOException {
        int port = 8066;

        try (DatagramSocket socket = new DatagramSocket(port)) {
            //接收数据
            byte[] data = new byte[1024];
            DatagramPacket packet = new DatagramPacket(data, data.length);
            socket.receive(packet);
            String info = new String(data,0, packet.getLength());
            System.out.println("服务器端接收：" + info);

            //响应数据
            //获取客户端的ip地址和端口号
            InetAddress address = packet.getAddress();
            int port1 = packet.getPort();
            byte[] data1 = "服务器端已收到数据!".getBytes();
            DatagramPacket packet1 = new DatagramPacket(data1, data1.length, address, port1);
            socket.send(packet1);
        }
    }
}
